from zope.interface import implements, Interface

from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from plone.memoize.instance import memoize

from my315ok.researchevent import researcheventMessageFactory as _
fmt = '%Y/%m/%d %H:%M:%S'

class IeventfolderView(Interface):
    """
    eventfolder view interface
    """

    def test():
        """ test method"""


class eventfolderView(BrowserView):
    """
    eventfolder browser view
    """
    implements(IeventfolderView)

    def __init__(self, context, request):
        self.context = context
        self.request = request

    @memoize
    def getsubobj(self,brain):
        
        catalog = getToolByName(self.context, 'portal_catalog')
        sepath= brain.getPath()
        query = {'meta_type':('ResearchAchievement'),
                 'sort_on':'getObjPositionInParent',
                 'sort_order':'forward',
                 'path':sepath,
                 }        
        sd = catalog(query)
        return sd
    
    def givevaltoreturnkey(self,dic,val):
#        import pdb
#        pdb.set_trace()
#        if type(val) == type(""):
#            val = val.decode("utf-8")
        for key in dic.keys():
            if dic[key] == val:
                return key
            else:
                continue            
        return ""
             
    def fetch_subject(self,brain):
        """ fetch subject of  a brain""" 

        keyword = brain.Subject
        if type(keyword) == type(()):
            keyword = keyword[0] 
        return keyword
        

    
    # here is set local varible item avoid by overed.
    @memoize
    def add_paras(self,brain):
        """given a research event brain,fetch research event title and all sub-objects (research achievement) parameters"""
#        import pdb
#        pdb.set_trace()
       
        tl = brain.Title
        desc = brain.Description
        subpara = self.hoteventurl(brain)
        subnum = len(subpara)
        tmp = "<a href='%s' title='%s'><span class ='researchevent'>%s</span></a>" % (brain.getURL(),desc,tl)
        subtile = ""
        if subnum > 0 :        
            for i in range(subnum):
                if i == 0:
                    char = ""
                else:
                    char = ","
                subtile = subtile + char + "<a href='%s' title='%s'><span class ='achievmns'>%s</span></a>" % (subpara[i]['url'],subpara[i]['des'],subpara[i]['title'])
          
            item = tmp + '(' + subtile + ')' 
        else:
            item = tmp                                                
        return item


        
    def hoteventurl(self,brain):
        """given a research event brain, fetch all sub-objects parameters"""

        subbrains = self.getsubobj(brain)
        paras = []            
        for ch in subbrains:
#            chobj = ch.getObject()
            chobjpara = self.fetch_achivemns(ch)
            paras.append(chobjpara)                
        return paras

                
            
                
    def fetch_achivemns(self,brain):
        """given a research achievement brain, fetch title , url ,description ,return parameters dic""" 

        keycodedic = {"M":'矩张量解',"O":'其他',"R":'破裂过程',"A":'台阵聚束'}
        subobjpara ={}                
        title = brain.Title
        url = brain.getURL()
        desc = brain.Description
                        
        try:
            keyword = self.fetch_subject(brain)
            code = self.givevaltoreturnkey(keycodedic, keyword)
        except:
            code = title 
        if code =="":
            code = title                
        subobjpara['title'] = code
        subobjpara['url'] = url
        subobjpara['des'] = desc
        return subobjpara

    def test(self,a,b,c):
#        import pdb
#        pdb.set_trace()
        if a:
            return b
        else:
            return c
    
    def toLocalizedTime(self, time, date_only=None, time_only=None):
        """Convert time to localized time
        """
        fmt = '%Y/%m/%d %H:%M:%S'
        datefmt = '%Y/%m/%d'
        timefmt  = '%H:%M:%S'
        if date_only:
            date = time.strftime(datefmt)
            return date
        elif time_only:
            time = time.strftime(timefmt)
            return time
        else:
            tmp = time.strftime(fmt)
            return tmp
        
class eventtopicView(eventfolderView):
    
        def parent(self,obj):
            parent = obj.aq_inner.aq_parent
            return parent
       
        
